import { ipcMain, BrowserWindow } from 'electron'
// import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import Client from 'ssh2-sftp-client'
import { spawn } from 'child_process'
console.log('11111111111111aaa啊啊啊啊啊')

ipcMain.handle('getConfigDate', () => {
  const data = fs.readFileSync('data.json', 'utf8')
  const obj = JSON.parse(data)
  return obj
})
ipcMain.handle('saveJson', (_event, val) => {
  fs.writeFileSync('data.json', val)
  const data = fs.readFileSync('data.json', 'utf8')
  const obj = JSON.parse(data)
  return obj
})
ipcMain.handle('ping2', (_event, val) => {
  const params = JSON.parse(val)
  // console.log(params)

  const child = spawn(params.packcommand, {
    cwd: params.packpath, // 设置工作目录为项目目录
    shell: true // 在某些操作系统中需要通过shell执行
    // stdio: 'inherit' // 可以看到子进程的输出
  })
  child.stdout.on('data', (data) => {
    console.log('success----------', data.toString())
  })
  child.on('error', (error) => {
    console.error(`error: ${error}`)
  })
  child.on('close', (code) => {
    BrowserWindow.fromWebContents(_event.sender)!.send('progressNotice', code)
    console.log(`------子进程退出，退出码：${code}`)
  })
  return
  const config = [
    {
      ip: params.ip,
      username: params.username,
      port: params.port,
      password: params.password, // ssh密码
      path: params.servePath, // 操作文件夹的配置地址路径/root/cicd/
      backupsPath: params.backupsPath,
      uploadpath: params.uploadpath // 上传文件夹地址路径
    }
  ]
  config.map((item) => {
    const sftp = new Client()
    sftp
      .connect({
        host: item.ip,
        port: item.port,
        username: item.username,
        password: item.password
      })
      .then(() => {
        console.log('bei-fen', 'aaa')
        BrowserWindow.fromWebContents(_event.sender)!.send('progressNotice', 1)

        return sftp.downloadDir(item.path, `${item.backupsPath}/${new Date().getTime()}`)
      })
      .then(() => {
        console.log('shan-chu', 'bbb')
        BrowserWindow.fromWebContents(_event.sender)!.send('progressNotice', 2)

        return sftp.rmdir(item.path, true)
      })
      .then(() => {
        console.log('chuan-chuan', 'ccc')
        BrowserWindow.fromWebContents(_event.sender)!.send('progressNotice', 3)
        return sftp.uploadDir(path.resolve(`${item.uploadpath}`), item.path)
      })
      .then(() => {
        console.log('sucess', 'ddd')
        BrowserWindow.fromWebContents(_event.sender)!.send('progressNotice', 4)
        sftp.end()
      })
      .catch((err) => {
        console.log('fail', 'eee', err)
        sftp.end()
      })
  })
})
